package cn.cloudtogo.server.mysql;

import cn.cloudtogo.common.ExternalDatasourceSpringTemplateContextRefresher;
import cn.cloudtogo.common.model.DatasourceTypes;
import cn.cloudtogo.common.model.ExternalDatasourceDao;
import cn.cloudtogo.common.model.ExternalDatasourceModel;
import cn.cloudtogo.common.types.ConnectString;
import cn.cloudtogo.common.types.Credential;
import cn.cloudtogo.common.types.Endpoint;
import cn.cloudtogo.common.types.RequestHeaderObject;
import cn.cloudtogo.common.util.JdbcConnectionHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author yaolianhua789@gmail.com
 **/
@Component
@Slf4j
public class SpringJdbcTemplateContextRefresher implements ExternalDatasourceSpringTemplateContextRefresher {

    private final SpringJdbcTemplateContext springJdbcTemplateContext;
    private final ExternalDatasourceDao externalDatasourceDao;

    public SpringJdbcTemplateContextRefresher(SpringJdbcTemplateContext springJdbcTemplateContext,
                                              ExternalDatasourceDao externalDatasourceDao) {
        this.springJdbcTemplateContext = springJdbcTemplateContext;
        this.externalDatasourceDao = externalDatasourceDao;
    }

    @Override
    public synchronized void refresh() {
        List<ExternalDatasourceModel> models = externalDatasourceDao.list()
                .stream()
                .filter(e -> Objects.equals(e.getType(), DatasourceTypes.Mysql))
                .collect(Collectors.toList());

        for (ExternalDatasourceModel model : models) {
            try {

                ConnectString connectString = new ConnectString(
                        DatasourceTypes.Mysql,
                        Credential.of(model.getUsername(), model.getPassword()),
                        Endpoint.of(model.getHost(), model.getPort()),
                        model.getSchema()
                );
                JdbcTemplate jdbcTemplate = JdbcConnectionHelper.getJdbcTemplate(connectString);

                RequestHeaderObject requestHeaderObject = RequestHeaderObject.ofModel(model);

                springJdbcTemplateContext.putJdbcTemplate(requestHeaderObject, jdbcTemplate);
            } catch (Exception e) {
                log.error("JdbcTemplate refresh error. \n {}", model);
            }


        }

//        List<String> projects = models.stream()
//                .map(ExternalDatasourceModel::getProject)
//                .collect(Collectors.toList());
//        log.debug("refresh spring jdbcTemplate context from datasource '{}'", projects);
    }
}
